// 2. 创建一个 Dio Provider，这是核心！
import 'package:casdon/app/config/env/env_provider.dart';
import 'package:casdon/core/encrypt/secure_encryptor.dart';
import 'package:casdon/core/network/dio_api_client.dart';
import 'package:casdon/core/network/encrypt_interceptor.dart';
import 'package:casdon/core/network/header_insert_Interceptor.dart';
import 'package:casdon/core/network/i_api_client.dart';
import 'package:casdon/core/network/ruiyun_interceptor.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

final dioProvider = Provider<Dio>((ref) {
  // 使用 ref.watch 来监听 environmentProvider 的变化
  // 当环境改变时，这个 dioProvider 会被自动重新创建
  final env = ref.watch(environmentProvider);
  final currentBaseUrl = env.main_url; // 假设 EnvConfig 中有 baseUrl 字段

  final options = BaseOptions(
    baseUrl: currentBaseUrl,
    connectTimeout: const Duration(seconds: 20),
    receiveTimeout: const Duration(seconds: 20),
    headers: {'Content-Type': 'application/json', 'clientId': env.clientId},
  );

  final dio = Dio(options);
  dio.interceptors.add(HeaderInsertInterceptor());
  dio.interceptors.add(EncryptInterceptor(ref.read(SecureEncryptorProvider)));
  dio.interceptors.add(const RuiyunInterceptor());
  // 在这里可以添加拦截器 (Interceptors)
  if (kDebugMode) {
    dio.interceptors.add(LogInterceptor(requestBody: true, responseBody: true));
  }
  return dio;
});

final apiClientProvider = Provider<IApiClient>((ref) {
  // 依赖 dioProvider 来获取 Dio 实例
  final dio = ref.watch(dioProvider);

  return DioApiClient(dio);
});
